import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/api/user.dart';
import 'package:flutter_enjoy_plus/utils/Emitter.dart';
import 'package:flutter_enjoy_plus/utils/Toast.dart';
import 'package:flutter_enjoy_plus/utils/TokenManager.dart';

class MinePage extends StatefulWidget {
  // const MinePage({super.key});
  const MinePage(
      {super.key,
      required this.currentIndex,
      required this.updateCurrentIndex});
  final int currentIndex;
  final Function(int) updateCurrentIndex;

  @override
  State<MinePage> createState() => _MinePageState();
}

class _MinePageState extends State<MinePage> {
  // 菜单数据
  final List menuList = [
    {
      "title": "我的房屋",
      "icon": "assets/images/house_profile_icon@2x.png",
    },
    {
      "title": "我的报修",
      "icon": "assets/images/repair_profile_icon@2x.png",
    },
    {
      "title": "访客记录",
      "icon": "assets/images/visitor_profile_icon@2x.png",
    }
  ];

  Map UserInfo = {'id': '', 'nickName': '', 'avatar': ''};
  //? 发送请求
  @override
  void didUpdateWidget(MinePage oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (widget.currentIndex == 1) {
      PromptAction.showSuccess('didUpdateWidget');
      //? 发送请求 -> 获取用户信息
      getUserInfo();
    }
  }

  @override
  void initState() {
    super.initState();
    // 订阅消息 LoginEvent
    registerLoginEvent();
  }

  registerLoginEvent() {
    eventBus.on<LoginEvent>().listen((event) {
      getUserInfo();
    });
  }

  getUserInfo() async {
    final res = await getUserInfoAPI();
    setState(() {
      UserInfo = res;
    });
  }

  List<Widget> getTitleChild() {
    return [
      ClipRRect(
        borderRadius: BorderRadius.circular(50.0),
        // child: Image.asset(
        //   'assets/images/avatar_1.jpg',
        //   width: 50,
        //   height: 50,
        // ),
        // child: UserInfo['avatar'] != null
        child: UserInfo['avatar'] != null && UserInfo['avatar'] != ''
            ? Image.network(UserInfo['avatar'], width: 50, height: 50)
            : Image.asset(
                'assets/images/avatar_1.jpg',
                width: 50,
                height: 50,
              ),
      ),
      const SizedBox(width: 10),
      // const Text('用户名', style: TextStyle(fontSize: 16, color: Colors.white)),
      Text(UserInfo['nickName'] ?? '用户名',
          style: const TextStyle(fontSize: 16, color: Colors.white)),
      // blank() 占据剩余空间
      const Spacer(),
      GestureDetector(
          onTap: () {
            final token = tokenManager.getToken();
            PromptAction.showSuccess('当前token是: $token');
            // //? 判断是否登录
            // if (token.isEmpty) {
            //   Navigator.pushNamed(context, '/login');
            // } else {
            //   Navigator.pushNamed(context, '/login');
            // }
            Navigator.pushNamed(context, '/profile');
          },
          child: const Row(
            children: [
              Text(
                '去完善信息',
                style: TextStyle(color: Colors.white),
              ),
              Icon(
                Icons.arrow_forward_ios,
                color: Colors.white,
                size: 13,
              )
            ],
          ))
    ];
  }

  List<Widget> getChildren() {
    return menuList
        .map(
          (item) => SizedBox(
            height: 50,
            child: Row(
              children: [
                Row(
                  children: [
                    Image.asset(
                      item['icon'],
                      width: 20,
                      height: 20,
                    ),
                    const SizedBox(
                      width: 10,
                    ),
                    Text(
                      item['title'],
                      style: const TextStyle(fontSize: 16),
                    )
                  ],
                ),
                const Spacer(),
                const Icon(
                  Icons.arrow_forward_ios,
                  size: 12,
                  color: Colors.grey,
                )
              ],
            ),
          ),
        )
        .toList();
  }

  _logout() {
    showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
              title: const Text('温馨提示'),
              content: const Text('确定要退出登录吗？'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  child: const Text('取消'),
                ),
                TextButton(
                  onPressed: () {
                    Navigator.pop(context);
                    //? 清除本地的token+refreshToken
                    tokenManager.deleteToken();
                    //? 更新用户信息->空
                    setState(() {
                      UserInfo = {'id': '', 'nickName': '', 'avatar': ''};
                    });
                    //? 底部首页tab切换为0首页
                    widget.updateCurrentIndex(0);
                  },
                  child: const Text('确认'),
                ),
              ]);
        });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(200, 85, 145, 175),
      appBar: AppBar(
        title: const Text(
          '我的',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.transparent,
        centerTitle: true,
      ),
      body: ListView(
        children: [
          // 个人信息
          Container(
            padding: const EdgeInsets.all(10),
            child: GestureDetector(
              onTap: () {
                Navigator.pushNamed(context, '/profile', arguments: UserInfo);
              },
              child: Row(
                children: getTitleChild(),
              ),
            ),
          ),
          Container(
            padding: const EdgeInsets.all(15),
            margin: const EdgeInsets.symmetric(vertical: 20, horizontal: 10),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(10),
            ),
            child: Column(
              children: getChildren(),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(
              left: 10,
              right: 10,
            ),
            child: Row(
              children: [
                Expanded(
                  child: ElevatedButton(
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.brown,
                      minimumSize: const Size(100, 50),
                    ),
                    onPressed: () {
                      _logout();
                    },
                    child: const Text(
                      '退出',
                      style: TextStyle(
                        color: Colors.white,
                      ),
                    ),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }
}
